package org.cytoscape.myapp.cytoscape_app_v1.internal.grupos;


import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.group.CyGroup;
import org.cytoscape.group.CyGroupFactory;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.group.events.GroupCollapsedEvent;
import org.cytoscape.group.events.GroupCollapsedListener;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.myapp.cytoscape_app_v1.internal.ViewUtil;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.view.presentation.property.BasicVisualLexicon;

public class Grupos  {

	private HashMap<String, CyGroup> grupos;
	private CyGroupManager mnGroup;
	private CyGroupFactory facGroup;
	private CyNetwork network;
	private CyApplicationManager applicationManager;
	
	
	public Grupos(CyGroupManager mnGroup, CyGroupFactory facGroup, List<String> names, CyNetwork network, CyApplicationManager applicationManager){
		this.mnGroup = mnGroup;
		this.facGroup = facGroup;
		this.network = network;
		this.applicationManager = applicationManager;
		this.grupos = new HashMap<String, CyGroup>();
	}
	
	public void addNode(CyNode node, String grupo){
		CyGroup grupoChoose = this.grupos.get(grupo);
		List<CyNode> lista = new Vector<CyNode>();
		lista.add(node);
		if (grupoChoose == null)
		{
			CyNode nodeDad = network.addNode();
			network.getRow(nodeDad).set(CyNetwork.NAME, grupo);
			//viewUtil.UpdateView(network);
			/*try{
			applicationManager.getCurrentNetworkView().getNodeView(nodeDad).setVisualProperty(BasicVisualLexicon.NODE_VISIBLE, false);
			}
			catch (Exception e){
				System.out.println("se rompio");
				e.printStackTrace();
			}*/
			CyGroup grup = facGroup.createGroup(network,nodeDad,true);
			//lista.add(nodeDad);
			grup.addNodes(lista);
			this.grupos.put(grupo, grup);
			mnGroup.addGroup(grup);
		}	
		else{
			
			grupoChoose.addNodes(lista);
			}
		
	}
	
	public void collapased(){
		Set<String> keys = grupos.keySet();
		for(String k:keys){
			CyGroup gp = grupos.get(k);
			if ((gp != null) && (!gp.isCollapsed(gp.getGroupNetwork())))
				gp.collapse(gp.getGroupNetwork());
		}
	}
	
	public void expand(){
		Set<String> keys = grupos.keySet();
		for(String k:keys){
			grupos.get(k).expand(grupos.get(k).getGroupNetwork());
		}
	}
	
	public void removeGroups(){
		Set<String> keys = grupos.keySet();
		Vector<CyNode> padres = new Vector<CyNode>();
		for(String k:keys){
			this.mnGroup.destroyGroup(grupos.get(k));
			padres.add(grupos.get(k).getGroupNode());
		}
		network.removeNodes(padres);
		
	}

}
